package com.wujilin.okra.fragment;

import static android.content.DialogInterface.BUTTON_POSITIVE;
import static com.wujilin.okra.Okra.EXTRA_CATEGORY_ID;
import static com.wujilin.okra.Okra.EXTRA_CATEGORY_NAME;
import static com.wujilin.okra.Okra.F_NAME;
import static com.wujilin.okra.Okra.T_CATEGORY;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.wujilin.okra.R;
import com.wujilin.okra.database.Sql;

/**
 * 
 * @author Belin Wu
 */
public class CategoryEditFragment extends DialogFragment implements DialogInterface.OnClickListener {
	private EditText categoryEdit;
	
	private Callback callback;
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		callback = (Callback) activity;
	}
	
	public static CategoryEditFragment newInstance(long id, String category) {
		Bundle args = new Bundle();
		args.putLong(EXTRA_CATEGORY_ID, id);
		args.putString(EXTRA_CATEGORY_NAME, category);
		
		CategoryEditFragment fragment = new CategoryEditFragment();
		fragment.setArguments(args);
		
		return fragment;
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_category, null);
		
		categoryEdit = (EditText) view.findViewById(R.id.category);
		String category = getArguments().getString(EXTRA_CATEGORY_NAME);
		categoryEdit.setText(category);
		categoryEdit.setSelection(category.length());
		
		Dialog dialog = new AlertDialog.Builder(getActivity())
				.setTitle(R.string.edit_category)
				.setView(view)
				.setPositiveButton(android.R.string.ok, this)
				.setNegativeButton(android.R.string.cancel, null)
				.create();
		return dialog;
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		if (which == BUTTON_POSITIVE) {
			String category = categoryEdit.getText().toString();
			long id = getArguments().getLong(EXTRA_CATEGORY_ID);
			boolean success = Sql.update(T_CATEGORY, id, F_NAME, category);
			if (success) {
				callback.onCategoryRenamed(category);
			}
		}
	}
	
	public static interface Callback {
		/**
		 * Called when the category renamed.
		 * 
		 * @param category The new name of category
		 */
		void onCategoryRenamed(String category);
	}
}
